package push.tools.service.service.egova;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import push.tools.service.entity.CaseBean;
import push.tools.service.entity.PageResultBean;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 获取案件列表
 */

@Service
public class PullCaseService {
    private static final Logger logger = LoggerFactory.getLogger(PullCaseService.class);

    // 每页的数据
    private static final int pageSize = 100;

    @Autowired
    public OkHttpClient okHttpClient;

    public List<CaseBean> getCaseList(String tag, String token, String startTime, String endTime, String url) {
        // 第一步：获取总数据量和第一页数据
        PageResultBean firstPageResult = getFirstPageAndTotalCount(token, startTime, endTime, url);
        if (firstPageResult.totalCount == 0) {
            logger.warn("{}请求完成,实际获取{}条数据,应获取{}条数据", tag, firstPageResult.firstPageData.size(), firstPageResult.totalCount);
            return firstPageResult.firstPageData;
        }
        List<CaseBean> allCases = Collections.synchronizedList(new ArrayList<>());//保证线程安全
        allCases.addAll(firstPageResult.firstPageData);
        // 第二步：如果有多页，并发请求剩余数据
        if (firstPageResult.totalPages > 1) {
            fetchRemainingPagesConcurrently(token, startTime, endTime, url, firstPageResult.totalPages, allCases);
        }
        // 数据完整性检查
        logger.warn("{}请求完成,实际获取{}条数据,应获取{}条数据", tag, allCases.size(), firstPageResult.totalCount);
        return allCases;
    }

    /**
     * 第一步：获取第一页数据和总数量
     */
    private PageResultBean getFirstPageAndTotalCount(String token, String startTime, String endTime, String url) {
        HashMap<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("start_time", startTime);
        paramsMap.put("end_time", endTime);
        paramsMap.put("pageIndex", 1);
        paramsMap.put("pageSize", pageSize);
        String paramsString = JSON.toJSONString(paramsMap);
        RequestBody body = RequestBody.create(paramsString, MediaType.get("application/json; charset=UTF-8"));
        Request request = new Request.Builder()//
                .addHeader("Authorization", "bearer " + token)//
                .url(url)//
                .post(body)//
                .build();//
        try (Response response = okHttpClient.newCall(request).execute()) {
            String respString = response.body().string();
            JSONObject jsonObject = (JSONObject) JSON.parse(respString);
            int totalCount = jsonObject.getIntValue("totalCount");//总数量
            if (totalCount == 0) {
                //封装结果
                PageResultBean bean = new PageResultBean();
                bean.totalCount = 0;
                bean.totalPages = 0;
                bean.firstPageData = new ArrayList<>();
                logger.warn("第1页请求完成，总页数0条数据");
                return bean;
            }
            JSONArray result = jsonObject.getJSONArray("result");//案件数组
            if (result == null || result.isEmpty()) {
                //封装结果
                PageResultBean bean = new PageResultBean();
                bean.totalCount = totalCount;
                bean.totalPages = 1;
                bean.firstPageData = new ArrayList<>();
                logger.warn("第1页请求完成,本页0条数据");
                return bean;
            }
            int totalPages = (totalCount + pageSize - 1) / pageSize;//计算总页数
            List<CaseBean> pageList = result.toJavaList(CaseBean.class);
            //封装结果
            PageResultBean bean = new PageResultBean();
            bean.totalCount = totalCount;
            bean.totalPages = totalPages;
            bean.firstPageData = pageList;
            logger.warn("第1页请求完成,本页{}条数据", result.size());
            return bean;
        } catch (Exception e) {
            throw new RuntimeException("获取第一页数据失败: " + e.getMessage());
        }
    }

    /**
     * 第二步：并发请求剩余页数
     */
    private void fetchRemainingPagesConcurrently(String token, String startTime, String endTime, String url, int totalPages, List<CaseBean> caseList) {
        List<CompletableFuture<Void>> futures = new ArrayList<>();
        for (int pageIndex = 2; pageIndex <= totalPages; pageIndex++) {
            final int currentPage = pageIndex;
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                try {
                    HashMap<String, Object> paramsMap = new HashMap<>();
                    paramsMap.put("start_time", startTime);
                    paramsMap.put("end_time", endTime);
                    paramsMap.put("pageIndex", currentPage);
                    paramsMap.put("pageSize", pageSize);
                    String paramsString = JSON.toJSONString(paramsMap);
                    RequestBody body = RequestBody.create(paramsString, MediaType.get("application/json; charset=UTF-8"));
                    Request request = new Request.Builder()//
                            .addHeader("Authorization", "bearer " + token)//
                            .url(url)//
                            .post(body)//
                            .build();
                    try (Response response = okHttpClient.newCall(request).execute()) {
                        String respString = response.body().string();
                        JSONObject jsonObject = (JSONObject) JSON.parse(respString);
                        JSONArray result = jsonObject.getJSONArray("result");
                        if (result != null && !result.isEmpty()) {
                            List<CaseBean> pageList = result.toJavaList(CaseBean.class);
                            caseList.addAll(pageList);
                            logger.warn("第{}页请求完成,本页{}条数据", currentPage, result.size());
                        } else {
                            logger.warn("第{}页返回结果为空", currentPage);
                        }
                    }
                } catch (Exception e) {
                    throw new RuntimeException("第" + currentPage + "页请求异常:" + e.getMessage());
                }
            });
            futures.add(future);
        }
        // 等待所有请求完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
    }

}
